<template>
  <div class="profile-page">
    <div class="page-header">
      <h1>个人中心</h1>
      <p>管理您的个人信息</p>
    </div>
    
    <div class="profile-content">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
            <el-button type="primary" @click="showEditDialog = true">
              <el-icon><Edit /></el-icon>
              编辑信息
            </el-button>
          </div>
        </template>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="4" animated />
        </div>
        
        <div v-else class="profile-info">
          <div class="avatar-section">
            <el-avatar :size="80">
              {{ userStore.userInfo?.name?.charAt(0) }}
            </el-avatar>
            <div class="user-basic">
              <h3>{{ userStore.userInfo?.name }}</h3>
              <p>{{ userStore.userInfo?.account }}</p>
            </div>
          </div>
          
          <div class="info-grid">
            <div class="info-item">
              <label>邮箱</label>
              <span>{{ userStore.userInfo?.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>手机号</label>
              <span>{{ userStore.userInfo?.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>性别</label>
              <span>{{ getSexText(userStore.userInfo?.sex) }}</span>
            </div>
            <div class="info-item">
              <label>部门</label>
              <span>{{ userStore.userInfo?.deptName || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>创建时间</label>
              <span>{{ formatDate(userStore.userInfo?.createdAt) }}</span>
            </div>
            <div class="info-item">
              <label>更新时间</label>
              <span>{{ formatDate(userStore.userInfo?.updatedAt) }}</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 密码修改卡片 -->
      <el-card class="password-card">
        <template #header>
          <span>修改密码</span>
        </template>
        
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          @submit.prevent="handlePasswordSubmit"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" :loading="passwordSubmitting" @click="handlePasswordSubmit">
              {{ passwordSubmitting ? '修改中...' : '修改密码' }}
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 编辑信息对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人信息"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account" disabled />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="editSubmitting" @click="handleEditSubmit">
          {{ editSubmitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, resetPassword } from '@/api/auth'
import dayjs from 'dayjs'

const userStore = useUserStore()

const loading = ref(false)
const editSubmitting = ref(false)
const passwordSubmitting = ref(false)
const showEditDialog = ref(false)

const editFormRef = ref<FormInstance>()
const editForm = reactive({
  account: '',
  name: '',
  email: '',
  phone: ''
})

const editRules: FormRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能少于8位', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$/, 
      message: '密码必须包含大小写字母、数字和特殊字符', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const fetchUserInfo = async () => {
  loading.value = true
  try {
    const result = await userStore.getUserInfoAction()
    if (result.success) {
      editForm.account = userStore.userInfo?.account || ''
      editForm.name = userStore.userInfo?.name || ''
      editForm.email = userStore.userInfo?.email || ''
      editForm.phone = userStore.userInfo?.phone || ''
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const resetEditForm = () => {
  if (userStore.userInfo) {
    editForm.account = userStore.userInfo.account
    editForm.name = userStore.userInfo.name
    editForm.email = userStore.userInfo.email || ''
    editForm.phone = userStore.userInfo.phone || ''
  }
  editFormRef.value?.resetFields()
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}

const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    editSubmitting.value = true
    
    const updateData = {
      id: userStore.userInfo?.id,
      account: editForm.account,
      email: editForm.email,
      phone: editForm.phone
    }
    
    await updateUserInfo(updateData)
    ElMessage.success('更新成功')
    showEditDialog.value = false
    fetchUserInfo()
  } catch (error) {
    ElMessage.error('更新失败')
  } finally {
    editSubmitting.value = false
  }
}

const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    passwordSubmitting.value = true
    
    await resetPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })
    
    ElMessage.success('密码修改成功')
    resetPasswordForm()
  } catch (error) {
    ElMessage.error('密码修改失败')
  } finally {
    passwordSubmitting.value = false
  }
}

const getSexText = (sex: number | undefined) => {
  if (sex === undefined) return '未设置'
  return sex === 1 ? '男' : sex === 0 ? '女' : '未设置'
}

const formatDate = (date: string | undefined) => {
  if (!date) return '未设置'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped lang="scss">
.profile-page {
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      font-size: 28px;
      color: #333;
      margin-bottom: 8px;
    }
    
    p {
      color: #666;
      font-size: 14px;
    }
  }
  
  .profile-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
    
    .profile-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .loading-container {
        padding: 20px 0;
      }
      
      .profile-info {
        .avatar-section {
          display: flex;
          align-items: center;
          gap: 16px;
          margin-bottom: 24px;
          padding-bottom: 24px;
          border-bottom: 1px solid #f0f0f0;
          
          .user-basic {
            h3 {
              font-size: 20px;
              color: #333;
              margin: 0 0 4px 0;
            }
            
            p {
              color: #666;
              font-size: 14px;
              margin: 0;
            }
          }
        }
        
        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 16px;
          
          .info-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
            
            label {
              font-size: 14px;
              color: #666;
              font-weight: 500;
            }
            
            span {
              font-size: 16px;
              color: #333;
            }
          }
        }
      }
    }
    
    .password-card {
      .el-form {
        .el-form-item {
          margin-bottom: 20px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr !important;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
}
</style>


